/**
 * fileName: MR_YLES_Check_item_barcode_CSV
 * @NApiVersion 2.1
 * @NScriptType MapReduceScript
 */


//异步校验CSV文件
import {EntryPoints} from 'N/types'
import search = require('N/search')
import file = require('N/file')
import record = require('N/record')
import log = require('N/log')
import url = require('N/url')
import runtime = require('N/runtime')
import email = require('N/email')
import {changeImportLog, getScriptParams, parseCsv, validateData} from "../tools/YLES_Tool";
import {CustomRecordType} from "../tools/YLES_RELATED_RECORDTYPE";
import {getAllItem, getCsvFolder} from "../tools/YLES_SEARCH_TOOL";

export function getInputData(cxt:EntryPoints.MapReduce.getInputDataContext) {
    //1.获取数据
    const logId = getScriptParams('custscript_yles_check_item_barcode_log') as string;
    log.debug('logId',logId);

    let rec = record.load({type: CustomRecordType().IMPORT_ITEM_BARCODE_LOG, id: logId});
    let st = rec.getValue({fieldId: 'custrecord_yles_status'});
    if (st != '2') throw 'wrong status.';
    let csvId = rec.getValue({fieldId: 'custrecord_yles_csvfile'}) as number;
    if (csvId > 0) {
        log.debug('csvId',csvId);
        const csvFile = file.load({id:csvId});
        //2:check csv
        const validateRes = validateData(csvFile,rec.id);
        log.debug('validateRes',validateRes);

        //更新导入日志
        changeImportLog(validateRes, logId);

        //发送校验邮件
        sendEmail(validateRes.ckErrorId);
        return null;
    }else {
        throw 'there are no deal data.'
    }
}
export function reduce(context: EntryPoints.MapReduce.reduceContext)  {

}


export function summarize(summary: EntryPoints.MapReduce.summarizeContext) {
    const logId = getScriptParams('custscript_yles_check_item_barcode_log') as string;
    log.debug("执行完成","end");

    //报错则重置状态
    if (summary.inputSummary.error) {
        record.submitFields({type: CustomRecordType().IMPORT_ITEM_BARCODE_LOG, id: logId, values: {custrecord_yles_status: '4'}});
    }

}


//发送邮件
function sendEmail(errId?: string | number) {
    const logId = getScriptParams('custscript_yles_check_item_barcode_log') as string;
    const userId = runtime.getCurrentUser().id;
    const recipientName = search.lookupFields({type: 'employee', id: userId, columns: ['firstname']})['firstname'];
    const targetUrl = "https://" +
        url.resolveDomain({
            hostType: url.HostType.APPLICATION
        }) +
        url.resolveScript({
            scriptId: 'customscript_yles_csv_item_barcode_im_sl',
            deploymentId: 'customdeploy_yles_csv_item_barcode_im_sl',
            params: {logId}
        })
    const subject = `【NetSuite Notice】Csv Check Progress is Completed.`;
    const body = `Hi ${recipientName}, 
        Your CSV has checked completed. Please click link below to view results:
        <br/>
        <a href='${targetUrl}'>view csv check results</a>
        <br><br>
        ${errId ? 'There are errors in this CSV. Click the link above for more details' : ''}
    `;
    email.send({
        author: userId,
        recipients: userId,
        subject: subject,
        body: body
    });
    log.debug({title: '邮件发送成功', details: 'email success'});
}